package thread.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 扩展线程池
 *
 * @author lwmzzz
 * @version 1.0
 * @date 2021/5/20 0:09
 */
public class Test05 {

    public static void main(String[] args) {
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(30)) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println(t.getId() + "线程准备执行任务：" + ((MyTask) r).taskName);
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("线程池退出");
            }
        };

        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(new MyTask("任务" + i));
        }

        threadPoolExecutor.shutdown();
    }


    private static class MyTask implements Runnable {
        private String taskName;

        public MyTask(String taskName) {
            this.taskName = taskName;
        }

        @Override
        public void run() {
            System.out.println(taskName + "任务正在被执行");

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
